float4x4 World;
float4x4 View;
float4x4 Projection;

sampler2D diffuse	: register(s0);
sampler2D normal	: register(s1);
sampler2D specular	: register(s2);

float3 lightPosition;
bool useNormalMap;

struct VertexShaderInput
{
    float3 Position : POSITION0;
	float3 normal	: NORMAL;
	float4 tangent	: TANGENT;
	float2 uv		: TEXCOORD;
};

struct VertexShaderOutput
{
    float4 Position			: POSITION;
	float4 worldPosition	: COLOR0;
	float2 uv				: TEXCOORD0;
	float3 normal			: COLOR1;
	float4 tangent			: COLOR2;
};

struct PixelIn
{
	float4 worldPosition	: COLOR0;
	float2 uv				: TEXCOORD0;
	float3 normal			: COLOR1;
	float4 tangent			: COLOR2;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = output.worldPosition = mul(float4(input.Position, 1.f), World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

	output.normal = mul(float4(input.normal, 0.0f), World);
	output.tangent = mul(input.tangent, World);
	output.uv = input.uv;

    return output;
}

float4 PixelShaderFunction(PixelIn input) : COLOR0
{
	///////////////////////////////////////////////////////////////////////////
	// calculate difuse value
	float4 difuse = tex2D(diffuse, input.uv);
	///////////////////////////////////////////////////////////////////////////
	// calculate normal value
	float3 normalMapVal = tex2D(normal, input.uv).xyz;
	normalMapVal = 2.f * normalMapVal - (float3)1.f;

	float3 normal = (float3)0;
		float3 tangent = input.tangent.xyz * input.tangent.w;
	if (useNormalMap)
	{

		float3 bitangent = cross(tangent, input.normal);
			float3x3 TBN = float3x3(input.normal, tangent, bitangent);

		normal = mul(float4(normalMapVal, 0.f), TBN);
	}
	else
		normal = input.normal;

	float3 to = normalize(lightPosition - input.worldPosition);
	float lambert = dot(normal, to);

	///////////////////////////////////////////////////////////////////////////
	// calculate specular value

	return difuse * lambert;
}

technique Technique1
{
    pass Pass1
    {
        // TODO: set renderstates here.

        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader = compile ps_3_0 PixelShaderFunction();
    }
}
